﻿namespace Dissemination.MVC.Controllers
{
    using System.Web.Mvc;
    using Dissemination.MVC.Repositories;
    using Dissemination.MVC.ViewModels;
    using Dissemination.MVC.Models;
    using System;
    using System.Data.SqlClient;

    public class TargetAreaController : ControllerBase
    {
        protected TargetAreaRepository repository = new TargetAreaRepository();

        #region List

        //
        // GET: /TargetArea/

        /// <summary>
        /// Returns the view associated to the list of entities in the data source.
        /// </summary>
        /// <param name="TargetAreaid"></param>
        /// <returns>Index view</returns>
        [Authorize(Roles = "Demostrator,Administrator")]
        public ActionResult Index(int programID)
        {
            if (log.IsDebugEnabled) log.Debug("Entering TargetAreas list...");
            if (log.IsDebugEnabled) log.Debug("Leaving TargetAreas list...");
            return View(repository.ListByProgramID(programID));
        }

        #endregion

        #region Details

        //
        // GET: /TargetArea/Details/5

        /// <summary>
        /// Returns the view associated to the details of an entity in the data source.
        /// </summary>
        /// <param name="id">The entity id.</param>
        /// <returns>Details view</returns>
        [Authorize(Roles = "Demostrator,Administrator")]
        public ActionResult Details(int id)
        {
            if (log.IsDebugEnabled) log.DebugFormat("Entering TargetArea details with id={0}...", id);
            TargetArea targetArea = repository.Get(id);
            
            if (targetArea == null)
            {
                if (log.IsErrorEnabled) log.ErrorFormat("TargetArea with id={0} not found", id);
                return View("NotFound");
            }

            if (log.IsDebugEnabled) log.DebugFormat("Leaving TargetArea details with id={0}...", id);
            return View(targetArea);
        }

        #endregion

        [Authorize(Roles = "Demostrator,Administrator")]
        public ActionResult Reporter(int id)
        {
            SurveyResultAndSeminarViewModel viewModel = new SurveyResultAndSeminarViewModel
            {
                TargetArea = repository.Get(id),
                SurveyResults = repository.GetSurveyResultsByTargetAreaID(id),
                Seminars = repository.GetSeminarsByTargetAreaID(id)
            };

            return View(viewModel);
        }


        #region New

        //
        // GET: /TargetArea/Create

        /// <summary>
        /// Creates the specified entity.
        /// </summary>
        /// <param name="programID">The entity</param>
        /// <returns>Details view</returns>
        [Authorize(Roles = "Administrator")]
        public ActionResult Create(int programID)
        {
            if (log.IsDebugEnabled) log.Debug("Entering TargetArea creation (GET)...");
            var viewModel = new TargetAreaViewModel
            {
                TargetArea = new TargetArea
                {
                        TargetAreaID = programID
                },
                Countries = repository.ListCountries()
                
            };

            if (log.IsDebugEnabled) log.Debug("Leaving TargetArea creation (GET)..."); 
            return View(viewModel);
        } 

        //
        // POST: /TargetArea/Create

        /// <summary>
        /// Creates the specified entity.
        /// </summary>
        /// <param name="targetArea">The entity</param>
        /// <returns>Details view</returns>
        [HttpPost]
        [Authorize(Roles = "Administrator")]
        public ActionResult Create(TargetArea targetArea)
        {
            if (log.IsDebugEnabled) log.Debug("Entering TargetArea creation (POST)...");
            int targetAreaProgramID = int.Parse(RouteData.Values["programID"].ToString());
            targetArea.Program = repository.GetProgramByProgramID(targetAreaProgramID);
            
            if (ModelState.IsValid)
            {

                try
                {
                    int targetAreaCountryID = int.Parse(Request["TargetArea.TargetAreaCountryID"]);

                    repository.Add(targetArea, targetAreaProgramID, targetAreaCountryID);

                    foreach (var survey in targetArea.Program.Surveys)
                    {
                        repository.AddEmptySurveyResult(survey, targetArea);
                    }

                    repository.Save();

                    if (log.IsDebugEnabled) log.Debug("Leaving TargetArea creation (POST)...");
                    return RedirectToAction("Details", "Program", new { id = targetArea.Program.ProgramID });
                }
                catch
                {
                }
            }

            var viewModel = new TargetAreaViewModel
            {
                TargetArea = new TargetArea
                {
                    Program = new Program
                    {
                        ProgramID = targetAreaProgramID
                    }
                },
                Countries = repository.ListCountries()

            };

            if (log.IsDebugEnabled)
            {
                //TODO: completar Create_TargetArea
            }

            return View(viewModel);
        }

        #endregion

        #region Edit

        //
        // GET: /TargetArea/Edit/5

        /// <summary>
        /// Returns the view associated with the edit of an existing entity.
        /// </summary>
        /// <param name="id">The id of the entity to edit</param>
        /// <returns>Edit view</returns>
        [Authorize(Roles = "Administrator")]
        public ActionResult Edit(int id)
        {
            if (log.IsDebugEnabled) log.DebugFormat("Entering TargetArea with id {0} edit (GET)...", id);
            TargetArea targetArea = repository.Get(id);
         
            if (targetArea == null)
               {
                if (log.IsErrorEnabled) log.ErrorFormat("TargetArea with id={0} not found", id);
                return View("NotFound");
            }

            var viewModel = new TargetAreaViewModel
            {
                TargetArea = targetArea,
                Countries = repository.ListCountries()
            };

            if (log.IsDebugEnabled) log.DebugFormat("Leaving TargetArea with id {0} edit (GET)...", id); 
            return View(viewModel);
        }

        //
        // POST: /TargetArea/Edit/5

        /// <summary>
        /// Edits the specified entity.
        /// </summary>
        /// <param name="id">The id of the existing entity.</param>
        /// <param name="collection">The collection of values entered.</param>
        /// <returns>Details view</returns>
        [HttpPost]
        [Authorize(Roles = "Administrator")]
        public ActionResult Edit(int id, FormCollection collection)
        {
            if (log.IsDebugEnabled) log.DebugFormat("Entering TargetArea with id {0} edit (POST)...", id);
            TargetArea targetArea = repository.Get(id);
            
            try
            {
                UpdateModel(targetArea, "TargetArea");

                repository.Save();

                if (log.IsDebugEnabled) log.DebugFormat("Leaving TargetArea with id {0} edit (POST)...", id);
                return RedirectToAction("Details", new { id = targetArea.TargetAreaID, TargetAreaID = Request["TargetAreaID"] });
            }
            catch (Exception ex)
            {
                var viewModel = new TargetAreaViewModel
                {
                    TargetArea = targetArea,
                    Countries = repository.ListCountries()
                };

                if (log.IsErrorEnabled) log.Error("Error editing TargetArea", ex); 
                return View(viewModel);
            }
        }

        #endregion

        #region Delete

        //
        // GET: /TargetArea/Delete/5

        /// <summary>
        /// Returns the view associated with a given entity to be deleted
        /// </summary>
        /// <param name="id">The id of the existing entity</param>
        /// <returns>Delete view</returns>
        [Authorize(Roles = "Administrator")]
        public ActionResult Delete(int id)
        {
            throw new NotImplementedException();

            if (log.IsDebugEnabled) log.DebugFormat("Entering TargetArea with id {0} delete (GET)...", id);
            TargetArea targetArea = repository.Get(id);

            if (targetArea == null)
            {
                if (log.IsErrorEnabled) log.ErrorFormat("TargetArea with id={0} not found", id);
                return View("NotFound");
            }

            if (log.IsDebugEnabled) log.DebugFormat("Leaving TargetArea with id {0} delete (GET)...", id);
            return View(targetArea);
        }

        //
        // POST: /TargetArea/Delete/5

        /// <summary>
        /// Deletes the specified entity.
        /// </summary>
        /// <param name="id">The id of the existing entity</param>
        /// <param name="confirmButton">The confirm button.</param>
        /// <returns>Deleted view</returns>
        [HttpPost]
        [Authorize(Roles = "Administrator")]
        public ActionResult Delete(int id, string confirmButton)
        {
            throw new NotImplementedException();

            try
            {
                if (log.IsDebugEnabled) log.DebugFormat("Entering TargetArea with id {0} delete (POST)...", id);
                TargetArea targetArea = repository.Get(id);

                if (targetArea == null)
                {
                    if (log.IsErrorEnabled) log.ErrorFormat("TargetArea with id={0} not found", id);
                    return View("NotFound");
                }

                int redirectProgramID = targetArea.Program.ProgramID;
                repository.Delete(targetArea);
                repository.Save();

                if (log.IsDebugEnabled) log.DebugFormat("Leaving TargetArea with id {0} delete (POST)...", id);
                return RedirectToAction("Details", "Program", new { id = redirectProgramID });
            }
            catch (Exception ex)
            {
                throw new ApplicationException("You can't delete this object because there are related items in the database.", ex.InnerException);
            }

        }

        #endregion

    }
}
